<?php


namespace App\Http\Services;

use App\Exceptions\ApiException;
use App\Exceptions\InvalidToken;
use App\Exceptions\WrongAccountException;
use App\Exceptions\WrongPasswordException;
use App\Libs\Token;
use App\Models\User;
use Illuminate\Support\Facades\Hash;

class AuthService extends BaseService
{

    /**
     * @param string $account
     * @param string $password
     * @return mixed
     * @throws WrongAccountException
     * @throws WrongPasswordException
     */
    public function login(string $account, string $password)
    {
        $found = User::where('email', $account)->get();
        if($found->isEmpty()) {
            throw new WrongAccountException();
        }

        $user = $found->first();
        if(!Hash::check($password, $user->password)) {
            throw new WrongPasswordException();
        }

        $user->api_token = Token::generate();
        $user->save();
        return $user;
    }

    /**
     * @param string $token
     * @return mixed
     * @throws InvalidToken
     */
    public function tokenToUser(string $token)
    {
        $found = User::where('api_token', $token)->get();
        if($found->isEmpty()) {
            throw new InvalidToken();
        }
        return $found->first();
    }
}